<?php

namespace app\cron\controller;

use app\app\model\ProjectRiskModel;
use app\app\model\ProjectTDModel;
use app\BaseController;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class UserMsg extends BaseController
{
    /**
     * 测试私信消息
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function test($msg)
    {
        $user = Db::table('sys_user')
            ->where('user_id', 23)
            ->field('nick_name')
            ->find();

        $nickname = $user['nick_name'];
        $date = date('Y年m月d日');


        $flag = preg_match_all('/\{\$(\w)+\}/', $msg, $matches);
        if ($flag) {
            foreach ($matches[0] as $v) {

                $var = substr($v, 2, strlen($v) - 3);
                $msg = str_replace($v, $$var, $msg);
            }
        }

        $insert_array = [];
        $insert_array[] = [
            'uid' => 23,
            'title' => '测试消息',
            'msg' => $msg,
            'jump_type' => 'none',
            'is_read' => 0,
            'is_push' => 0,
            'create_time' => date('Y-m-d H:i:s'),
        ];

        Db::table('t_user_msg')->insertAll($insert_array);

        $this->success('success');
    }

    /**
     * 测试私信消息清除
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function testClear()
    {
        Db::table('t_user_msg')
            ->where('title', '测试消息')
            ->where('uid', 23)
            ->delete();

        $this->success('success');
    }

    /**
     * 单推消息
     * @param $uid
     * @param $title
     * @param $msg
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function single($uid, $title, $msg)
    {
        $user = Db::table('sys_user')
            ->where('user_id', $uid)
            ->field('nick_name')
            ->find();

        $nickname = $user['nick_name'];
        $date = date('Y年m月d日');

        $flag = preg_match_all('/\{\$(\w)+\}/', $msg, $matches);
        if ($flag) {
            foreach ($matches[0] as $v) {

                $var = substr($v, 2, strlen($v) - 3);
                $msg = str_replace($v, $$var, $msg);
            }
        }

        $insert_array[] = [
            'uid' => $uid,
            'title' => $title,
            'msg' => $msg,
            'jump_type' => 'none',
            'is_read' => 0,
            'is_push' => 0,
            'create_time' => date('Y-m-d H:i:s'),
        ];

        Db::table('t_user_msg')->insertAll($insert_array);

        $this->success('success');
    }

    /**
     * 公告广播消息
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function boardCast($title, $msg)
    {
        $date = date('Y年m月d日');

        $user_id_array = Db::table('sys_user')
            ->field('user_id')
            ->select();
        empty($user_id_array) && $this->error('未找到合适的用户');
        $user_id_array = array_column($user_id_array->toArray(), 'user_id');
        $user_id_array = array_unique($user_id_array);

        $flag = preg_match_all('/\{\$(\w)+\}/', $msg, $matches);

        $insert_array = [];
        foreach ($user_id_array as $uid) {
            $user = Db::table('sys_user')
                ->where('user_id', $uid)
                ->field('nick_name')
                ->find();

            $nickname = $user['nick_name'];

            $tmp_msg = $msg;
            if ($flag) {
                foreach ($matches[0] as $v) {
                    $var = substr($v, 2, strlen($v) - 3);
                    $tmp_msg = str_replace($v, $$var, $tmp_msg);
                }
            }

            $insert_array[] = [
                'uid' => $uid,
                'title' => $title,
                'msg' => $msg,
                'jump_type' => 'none',
                'is_read' => 0,
                'is_push' => 0,
                'create_time' => date('Y-m-d H:i:s'),
            ];
        }

        Db::table('t_user_msg')->insertAll($insert_array);

        $this->success('success');
    }

    /**
     * 群推
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function group($role_id, $title, $msg)
    {
        $date = date('Y年m月d日');

        $user_id_array = Db::table('sys_user_role')
            ->where('role_id', 'in', $role_id)
            ->field('user_id')
            ->select();
        empty($user_id_array) && $this->error('未找到合适的用户');
        $user_id_array = array_column($user_id_array->toArray(), 'user_id');
        $user_id_array = array_unique($user_id_array);

        $flag = preg_match_all('/\{\$(\w)+\}/', $msg, $matches);

        $insert_array = [];
        foreach ($user_id_array as $uid) {
            $user = Db::table('sys_user')
                ->where('user_id', $uid)
                ->field('nick_name')
                ->find();

            $nickname = $user['nick_name'];

            $tmp_msg = $msg;
            if ($flag) {
                foreach ($matches[0] as $v) {
                    $var = substr($v, 2, strlen($v) - 3);
                    $tmp_msg = str_replace($v, $$var, $tmp_msg);
                }
            }

            $insert_array[] = [
                'uid' => $uid,
                'title' => $title,
                'msg' => $tmp_msg,
                'jump_type' => 'none',
                'is_read' => 0,
                'is_push' => 0,
                'create_time' => date('Y-m-d H:i:s'),
            ];
        }

        Db::table('t_user_msg')->insertAll($insert_array);

        $this->success('success');
    }

    /**
     * 每周提示
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function weeklyMsg()
    {
        $data = $this->riskTotal();

        $msg = "本周预计有{$data['risk_num']}个二级风险，{$data['power_num']}个停电计划，{$data['power_five_num']}个五级电网事件风险，请关注现场作业情况。";

        $user_id_array = Db::table('sys_user_role')
            ->where('role_id', 'in', [3, 6])
            ->field('user_id')
            ->select();
        $user_id_array = array_column($user_id_array->toArray(), 'user_id');
        $user_id_array = array_unique($user_id_array);

        $insert_array = [];
        foreach ($user_id_array as $v) {
            $insert_array[] = [
                'uid' => $v,
                'title' => '本周计划',
                'msg' => $msg,
                'jump_type' => 'none',
                'is_read' => 0,
                'is_push' => 0,
                'create_time' => date('Y-m-d H:i:s'),
            ];
        }

        Db::table('t_user_msg')->insertAll($insert_array);

        $this->success('success');
    }

    /**
     * 每周提示
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function dailyMsg()
    {
        $date = date('Y年m月d日');

        $data = $this->riskTotal();

        $msg = "您好；建设分公司{$date}，建设情况如下：今天有二级风险${data['risk_num']}个，现场停电作业{$data['power_num']}项，五级电网事件风险{$data['power_five_num']}项，请查收！感谢您一天幸苦的工作！";

        $user_id_array = Db::table('sys_user_role')
            ->where('role_id', 'in', [3, 6])
            ->field('user_id')
            ->select();
        $user_id_array = array_column($user_id_array->toArray(), 'user_id');
        $user_id_array = array_unique($user_id_array);

        $insert_array = [];
        foreach ($user_id_array as $v) {
            $user = Db::table('sys_user')
                ->where('user_id', $v)
                ->field('nick_name')
                ->find();

            $nickname = $user['nick_name'];

            $insert_array[] = [
                'uid' => $v,
                'title' => '本周计划',
                'msg' => $nickname . $msg,
                'jump_type' => 'none',
                'is_read' => 0,
                'is_push' => 0,
                'create_time' => date('Y-m-d H:i:s'),
            ];
        }

        Db::table('t_user_msg')->insertAll($insert_array);

        $this->success('success');
    }

    /**
     *  本周计划二级风险数、停电数、五级风险事件个数
     *  定时更新打卡时间
     */
    public function riskTotal()
    {
        //获取本周开始时间
        $time = $this->getTime('week');

        //获取本周二级风险数
        $where_risk[] = ['start_time', '<=', $time['end_time']];
        $where_risk[] = ['end_time', '>=', $time['start_time']];
        $risk_num = ProjectRiskModel::where($where_risk)->where('risk_level', '=', 2)->count();

        //获取本周停电数、五级风险事件个数
        $where_power[] = ['start_date', '<=', $time['end_time']];
        $where_power[] = ['end_date', '>=', $time['start_time']];
        $power_num = ProjectTDModel::where($where_power)->count();
        $power_five_num = ProjectTDModel::where($where_power)->where('is_high_risk', '是')->count();

        return [
            'risk_num' => $risk_num,
            'power_num' => $power_num,
            'power_five_num' => $power_five_num,
        ];
    }
}